/**
 * JS中的哈希表
 * 由于JS中没有哈希表的结构，手动实现一个
 * 如果不需要value值，直接用JS的Set对象更快
 * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Set
 */
class HashMap {
    constructor(keyIsNumber = false) {
        this.tree = {};
        this.keyIsNumber = keyIsNumber;
    }

    add(key, value = null) {
        if (this.tree.hasOwnProperty(key)) {
            return;
        }
        this.tree[key] = value;
    }

    getByKey(key) {
        if (this.tree.hasOwnProperty(key)) {
            return this.tree[key];
        }

        return null;
    }

    setByKey(key, value) {
        this.tree[key] = value;
    }

    removeKey(key) {
        if (this.tree.hasOwnProperty(key)) delete this.tree[key];
    }

    keys() {
        if (this.keyIsNumber) {
            let arr = Object.keys(this.tree);
            return arr.map((ele) => parseInt(ele));
        }
        return Object.keys(this.tree);
    }

    values() {
        return Object.values(this.tree);
    }

    all() {
        return Object.assign({}, this.tree);
    }
}

module.exports = HashMap;

// test
// let hash = new HashMap();
// hash.add(1, 'a');
// hash.add(1, 'fdjsk');
// hash.add(2, 'b');
// hash.add(3, 'c');
// console.log(hash.getByKey(1));
// console.log(hash.keys());
// console.log(hash.all());

// console.log(`hash remove property 1`);
// hash.removeKey('1');
// console.log(hash.all());
